package top.hundreds.oasys.service;

import org.springframework.stereotype.Service;
import top.hundreds.common.crud.service.BaseService;
import top.hundreds.oasys.bean.converter.Converter;
import top.hundreds.oasys.bean.entity.Personnel;
import top.hundreds.oasys.bean.entity.User;
import top.hundreds.oasys.bean.enums.CommonStatus;
import top.hundreds.oasys.bean.vo.PersonnelVo;
import top.hundreds.oasys.bean.vo.UserVo;
import top.hundreds.oasys.mapper.PersonnelMapper;
import top.hundreds.oasys.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author lcf
 * @since 2021-01-27 15:01:38
 */
@Service("userService")
public class UserService extends BaseService<User, UserMapper> {

    @Resource
    private Converter<User,UserVo> userVoBuilder;

    @Resource
    private Converter<Personnel, PersonnelVo> personnelVoBuilder;

    @Resource
    private PersonnelMapper personnelMapper;

    public UserVo buildVo(User user) {
        UserVo userVo = new UserVo();
        userVoBuilder.buildVo(user,userVo);
        userVo.setStatusName(CommonStatus.formValue(userVo.getStatus()).getLabel());
        if(user.getPersonnelId() != -1){
            Personnel personnel = personnelMapper.selectById(user.getPersonnelId());
            userVo.setPersonnelName(personnel.getName());
            List<PersonnelVo> personnelVoList = getParentVo(personnel.getId());
            Collections.reverse(personnelVoList);
            userVo.setDepartmentList(personnelVoList);
        }
        return userVo;
    }

    private List<PersonnelVo> getParentVo(Long personnelId){
        Personnel personnel = personnelMapper.selectById(personnelId);
        PersonnelVo personnelVo = new PersonnelVo();
        personnelVoBuilder.buildVo(personnel,personnelVo);
        List<PersonnelVo> parentVoList;
        if(personnel.getParentId()!= -1){
            parentVoList = getParentVo(personnel.getParentId());
        }else {
            parentVoList = new ArrayList<>();
        }
        parentVoList.add(personnelVo);
        return parentVoList;
    }

}
